
# Import settings.
from settings import *

# Log a message each time this module get loaded.
logging.info('Loading %s', __name__)


# Import datastore models.
from model import *



class Main(webapp.RequestHandler):
  # Splash Page Entity.
  def get(self):
    logging.debug('Viewing Splash Page')
    template_values = {}
    path = tpl_path('home.html')
    self.response.out.write(template.render(path, template_values))

    
    
# #######################
# LOAD QUIZZES
# #######################

class InfluenceQuiz(webapp.RequestHandler):
  # Taught Or Not Quiz Model.
  def get(self):
    logging.debug('Viewing Influence Quiz')
    global LOGINSTATUS

    template_values = {
      'url': login_url(self.request.uri),
      'login_status' : LOGINSTATUS,
      'url_linktext': login_text(),
      'influence': random.choice(['influenced', 'influenced_by']),
      }
     
      
    path = tpl_path('influence_quiz.html')
    self.response.out.write(template.render(path, template_values))
    

class DeathQuiz(webapp.RequestHandler):
  def get(self):
    logging.debug('Viewing Death Quiz')
    
    global LOGINSTATUS

    template_values = {
      'url': login_url(self.request.uri),
      'login_status' : LOGINSTATUS,
      'url_linktext': login_text(),
      'correct_top': random.choice(['true', 'false']),
       }
      
    path = tpl_path('death_quiz.html')
    self.response.out.write(template.render(path, template_values))


# #######################
# VIEW SCORES
# #######################

  
class InfluenceViewScore(webapp.RequestHandler):
  # View Taught Or Not Grade.
   def get(self):
    logging.debug('Loading Influence Score')
    
    try:
      grades = InfluenceGrade.gql("WHERE author = :author ORDER BY date DESC",
                               author=users.get_current_user())
      latest_grades = InfluenceGrade.gql("WHERE author = :author ORDER BY date DESC LIMIT 6",
                               author=users.get_current_user())   
      logging.info('Loading all InfluenceGrade items user %s'
                   % users.get_current_user().nickname())
    except:
      raise_error('Error Retrieving Data From InfluenceGrade Model: %s'
                    % users.get_current_user())
    
    try:
      correct_item = InfluenceGrade.gql("WHERE score = :1 AND author = :2",
                             "correct", users.get_current_user() )
      logging.info('Loading correct InfluenceGrade items user %s'
                   % users.get_current_user().nickname())
    except:
      raise_error('Error Retrieving Data From InfluenceGrade Model: %s'
                    % users.get_current_user())    
	  
    totalscore = correct_item.count()
    totalitems = grades.count()
    percentage = 0
    if totalitems > 0:
      percentage = float(totalscore) / float(totalitems) * 100
      percentage = int(percentage) 
   
    template_values = {
      'grades': latest_grades,
      'totalscore': totalscore,
      'totalitems': totalitems,
      'percentage': percentage,
      'url': login_url(self.request.uri),
      'url_linktext': login_text(),
     
   }
     
      
    path = tpl_path('influence_score.html')
    self.response.out.write(template.render(path, template_values))
  

class DeathViewScore(webapp.RequestHandler):
   # View Shot Or Not Grade.
   def get(self):
    logging.debug('Loading Death Score')
    
    try:
      grades = DeathGrade.gql("WHERE author = :author ORDER BY date DESC",
                               author=users.get_current_user())
      latest_grades = DeathGrade.gql("WHERE author = :author ORDER BY date DESC LIMIT 6",
                               author=users.get_current_user())      
      logging.info('Loading all DeathGrade items user %s'
                   % users.get_current_user().nickname())
    except:
      raise_error('Error Retrieving Data From DeathGrade Model: %s'
                    % users.get_current_user())
      
    try:
      correct_item = DeathGrade.gql("WHERE score = :1 AND author = :2",
                             "correct", users.get_current_user() )
      logging.info('Loading correct DeathGrade items user %s'
                   % users.get_current_user().nickname())

    except:
      raise_error('Error Retrieving Data From DeathGrade Model: %s'
                    % users.get_current_user())
	  
    totalscore = correct_item.count()
    totalitems = grades.count()
    percentage = 0
    if totalitems > 0:
      percentage = float(totalscore) / float(totalitems) * 100
      percentage = int(percentage) 

    template_values = {
      'grades': latest_grades,
      'totalscore': totalscore,
      'totalitems': totalitems,
      'percentage': percentage,
      'url': login_url(self.request.uri),
      'url_linktext': login_text(),
     
   }
     
      
    path = tpl_path('death_score.html')
    self.response.out.write(template.render(path, template_values))

    
    
# #######################
# STORE QUIZ SCORES
# #######################



class InfluenceTurnIn(webapp.RequestHandler):
  # Store Taught Or Not Grade.

  def get(self):
    logging.debug('Posting Influence Grade')

     
    global LOGINSTATUS

    if users.get_current_user():
        
      grade = InfluenceGrade()   
      grade.subject_name = self.request.get('subject_name')
      grade.subject_id = self.request.get('subject_id')
      grade.object_id = self.request.get('object_id')
      grade.object_name = self.request.get('object_name')
      grade.influence_type = self.request.get('influence_type')
      grade.author = users.get_current_user()
      LOGINSTATUS = users.get_current_user()

      if self.request.get('answer') == "_app":
         grade.score = "correct"
      else:
         grade.score = "incorrect"
      
      try:
        grade.put()
        logging.info('InfluenceGrade entered by user %s'
                     % users.get_current_user().nickname())
      except:
        raise_error('Error saving grade for user %s, with score %s: %s %s'
                      % grade.author, grade.score, grade.subject_id,
                      grade.object_id)

    else:
      LOGINSTATUS = "not_logged_in"
      logging.info('User Not Logged In')
     
    self.redirect('/taught')


  

class DeathTurnIn(webapp.RequestHandler):
  # Store Shot Or Not Grade.
  def get(self):
    logging.debug('Posting Death Grade')
    
    global LOGINSTATUS

    if users.get_current_user():
      grade = DeathGrade()
      grade.subject_name = self.request.get('subject_name')
      grade.subject_id = self.request.get('subject_id')
      grade.cause = self.request.get('_cause')
      grade.fake_cause = self.request.get('cause')      
      grade.author = users.get_current_user()
      LOGINSTATUS = users.get_current_user()      
      if self.request.get('death_type') == self.request.get('_cause'):
         grade.score = "correct"
      else:
         grade.score = "incorrect"
         
      try:
        grade.put()
        logging.info('DeathGrade entered by user %s'
                     % users.get_current_user().nickname())
      except:
        raise_error('Error saving grade for user %s, with score %s: %s %s'
                      % grade.author, grade.score, grade.subject_id,
                      grade.object_id)
      
    else:
      LOGINSTATUS = "not_logged_in"
      logging.info('User Not Logged In')


      
    self.redirect('/shot')
    

